package com.smartkey.ui;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.project.smartkey.R;
import com.smartkey.activity.SettingActivity;
import com.smartkey.adapter.MainAppListAdapter;
import com.smartkey.adapter.MainPagerAdapter;
import com.smartkey.bean.AppInfo;
import com.smartkey.constant.Constant;
import com.smartkey.sharedpreferences.SharePreferencesUtil;
import com.smartkey.utils.AppUtil;
import com.smartkey.utils.SetListViewHeightUtil;

/**
 * 应用主页面 Tab页面手势滑动切换以及动画效果
 * 
 * 
 */
public class MainActivity extends Activity implements OnClickListener {
	// ViewPager是google SDk中自带的一个附加包的一个类，可以用来实现屏幕间的切换。
	// android-support-v4.jar
	public static ViewPager mPager;// 页卡内容
	private List<View> listViews; // Tab页面列表
	private ImageView cursor;// 动画图片
	private ImageView more;// 动画图片
	private TextView t1, t2, t3;// 页卡头标
	private int offset = 0;// 动画图片偏移量
	private int currIndex = 0;// 当前页卡编号
	private int bmpW;// 动画图片宽度

	PopupWindow pop;

	RadioGroup radiogroup;

	private int currentView;

	// private View view ;

	private ArrayList<AppInfo> appList;
	private MainAppListAdapter adapter;

	public static int GET_APP_OK = 100;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		InitImageView();
		InitTextView();
		InitViewPager();

		initTestView();
	}

	private void initTestView() {
		findViewById(R.id.test_single_click).setOnClickListener(this);
		findViewById(R.id.test_double_click).setOnClickListener(this);
	}

	/**
	 * 初始化头标
	 */
	private void InitTextView() {
		t1 = (TextView) findViewById(R.id.text1);
		t2 = (TextView) findViewById(R.id.text2);
		t3 = (TextView) findViewById(R.id.text3);

		t1.setOnClickListener(new MyOnClickListener(0));
		t2.setOnClickListener(new MyOnClickListener(1));
		t3.setOnClickListener(new MyOnClickListener(2));
		more = (ImageView) findViewById(R.id.img_more);
		more.setOnClickListener(this);

	}

	/**
	 * 初始化ViewPager
	 */
	private void InitViewPager() {
		mPager = (ViewPager) findViewById(R.id.vPager);
		listViews = new ArrayList<View>();
		currentView = 0;
		listViews.add(getView());
		currentView = 1;
		listViews.add(getView());
		currentView = 2;
		listViews.add(getView());

		mPager.setAdapter(new MainPagerAdapter(this, listViews));
		mPager.setCurrentItem(0);
		mPager.setOnPageChangeListener(new MyOnPageChangeListener());

	}

	/**
	 * 获取viewpager的子界面
	 */
	private View getView() {
		LayoutInflater mInflater = getLayoutInflater();
		View view = mInflater.inflate(R.layout.lay2, null);
		initListview(view);
		return view;
	}

	/**
	 * 获取应用入口
	 * 
	 * @param view
	 */
	private void initGetMoreAppView(final View view) {
		RelativeLayout getMoreApp = (RelativeLayout) view
				.findViewById(R.id.rl_get_more_app);
		getMoreApp.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						AppListActivity.class);
				startActivityForResult(intent, 0);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == GET_APP_OK) {
			Bundle b = data.getExtras(); // data为B中回传的Intent
			String packageName = b.getString("PackageName");
			if (!packageName.equals("")) {
				// 保存到sharedpreferences
				SharePreferencesUtil util = new SharePreferencesUtil(
						MainActivity.this);
				util.setCheckAppPackageName(packageName);

				View view = listViews.get(mPager.getCurrentItem());
				initListview(view);
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/**
	 * 重置listview
	 */
	private void initListview(final View view) {
		// if (appList == null) {
		appList = (ArrayList<AppInfo>) AppUtil
				.getAllCheckAppInfo(MainActivity.this);
		// }

		initGetMoreAppView(view);// 获取应用入口

		final ListView listview = (ListView) view
				.findViewById(R.id.main_listview);

		String check;
		SharePreferencesUtil util = new SharePreferencesUtil(this);
		if (currentView == 0) {
			check = util.getSingleClickValue();
		} else {
			check = util.getDoubleClickValue();
		}

		adapter = new MainAppListAdapter(MainActivity.this, appList, check);
		listview.setAdapter(adapter);
		// 调整listview高度
		SetListViewHeightUtil.setListViewHeightBasedOnChildren(listview);

		listview.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// for (int i = 0; i < appList.size(); i++) {
				AppInfo info = appList.get(arg2);
				// if (i == arg2) {
				// info.isCheck = true;
				final SharePreferencesUtil preUtil = new SharePreferencesUtil(
						MainActivity.this);
				if (mPager.getCurrentItem() == 0) { // 单击
					preUtil.setSingleClickValue(info);
				} else if (mPager.getCurrentItem() == 1) { // 双击
					preUtil.setDoubleClickValue(info);
				} else { // 三连击
					preUtil.setTrifecta(info);
				}
				// } else {
				// info.isCheck = false;
				// }
				// }
				// adapter.resetData(info.packageName);
				// adapter.notifyDataSetChanged();
				// resetListview(view);
				resetListview(listview);

			}
		});
	}

	/**
	 * 重置listview
	 */
	private void resetListview(ListView listview) {
		final int currentItem = mPager.getCurrentItem();
		// ListView listview = (ListView) view.findViewById(R.id.main_listview);
		MainAppListAdapter adapter = (MainAppListAdapter) listview.getAdapter();
		String check;
		SharePreferencesUtil util = new SharePreferencesUtil(this);
		if (currentItem == 0) {
			check = util.getSingleClickValue();
		} else if (currentItem == 1){
			check = util.getDoubleClickValue();
		}else{
			check = util.getTrifectaClickValue();
		}
		adapter.resetData(check);
		adapter.notifyDataSetChanged();
	}

	/**
	 * 初始化动画
	 */
	private void InitImageView() {
		cursor = (ImageView) findViewById(R.id.cursor);
		bmpW = BitmapFactory.decodeResource(getResources(), R.drawable.a)
				.getWidth();// 获取图片宽度
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int screenW = dm.widthPixels;// 获取分辨率宽度
		offset = (screenW / 3 - bmpW) / 3;// 计算偏移量
		Matrix matrix = new Matrix();
		matrix.postTranslate(offset, 0);
		cursor.setImageMatrix(matrix);// 设置动画初始位置
	}

	/**
	 * 头标点击监听
	 */
	public class MyOnClickListener implements View.OnClickListener {
		private int index = 0;

		public MyOnClickListener(int i) {
			index = i;
		}

		@Override
		public void onClick(View v) {
			mPager.setCurrentItem(index);
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) { // 监听菜单键
			// 模拟点击下拉按钮
			if (pop != null && pop.isShowing()) {
				pop.dismiss();
			} else {
				more.performClick();
			}
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 页卡切换监听
	 */
	public class MyOnPageChangeListener implements OnPageChangeListener {

		int one = offset * 3 + bmpW;// 页卡1 -> 页卡2 偏移量

		@Override
		public void onPageSelected(int arg0) {
			Animation animation = null;
			switch (arg0) {
			case 0:
				animation = new TranslateAnimation(one, 0, 0, 0);
				break;
			case 1:
				animation = new TranslateAnimation(offset, one, 0, 0);
				break;
			case 2:
				animation = new TranslateAnimation(offset + one, one * 2, 0, 0);
				break;
			}
			currIndex = arg0;
			animation.setFillAfter(true);// True:图片停在动画结束位置
			animation.setDuration(300);
			cursor.startAnimation(animation);
		}

		@Override
		public void onPageScrolled(int arg0, float arg1, int arg2) {
		}

		@Override
		public void onPageScrollStateChanged(int arg0) {
		}
	}

	/**
	 * 按键监听
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.img_more:
			// Intent intent = new Intent(this, SettingsActicity.class);
			// startActivity(intent);
			showPopMenu(v);
			break;
		case R.id.add_app:
			Intent intent = new Intent(this, AppListActivity.class);
			startActivity(intent);
			break;
		case R.id.test_single_click:
			// SharePreferencesUtil util = new SharePreferencesUtil(this);
			// String packageName = util.getSingleClickValue();
			// AppUtil.launchAppByPackageName(this, packageName);
			Intent clickIntent1 = new Intent("com.smartkey.click");
			clickIntent1.putExtra("msg", Constant.SINGLGE_CLICK);
			sendBroadcast(clickIntent1);
			break;
		case R.id.test_double_click:
			// SharePreferencesUtil util1 = new SharePreferencesUtil(this);
			// String packageName1 = util1.getDoubleClickValue();
			// AppUtil.launchAppByPackageName(this, packageName1);
			Intent clickIntent2 = new Intent("com.smartkey.click");
			clickIntent2.putExtra("msg", Constant.DOUBLE_CLICK);
			sendBroadcast(clickIntent2);
			break;

		default:
			break;
		}
	}

	/**
	 * 显示/隐藏下拉菜单
	 */
	private void showPopMenu(View v) {
		if (pop == null) {
			initPopMenu();
		}
		if (pop.isShowing()) {
			// 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
			pop.dismiss();
		} else {
			// 显示窗口
			pop.showAsDropDown(v);
		}
	}

	/**
	 * 初始化popMenu pop菜单事件设置方法
	 */
	private void initPopMenu() {
		LayoutInflater inflater = LayoutInflater.from(this);
		// 引入窗口配置文件
		View view = inflater.inflate(R.layout.monthactivity_menu, null);
		Button settings = (Button) view.findViewById(R.id.pop_btn_settings);// 设置按键
		Button checkupdate = (Button) view
				.findViewById(R.id.pop_btn_checkupdate);// 检查更新按键
		Button feedback = (Button) view.findViewById(R.id.pop_btn_feedback);// 用户反馈按键

		settings.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(MainActivity.this,
						SettingActivity.class);
				startActivity(intent);
			}
		});

		// 创建PopupWindow对象
		pop = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT, false);
		// 需要设置一下此参数，点击外边可消失
		pop.setBackgroundDrawable(new BitmapDrawable());
		// 设置点击窗口外边窗口消失
		pop.setOutsideTouchable(true);
		// 设置此参数获得焦点，否则无法点击
		pop.setFocusable(true);
		pop.setTouchable(true);

		// 点击手机菜单键后，达到显示/隐藏popmenu效果要下下面这两句
		view.setFocusableInTouchMode(true);
		view.setOnKeyListener(new OnKeyListener() {
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_DOWN
						&& keyCode == KeyEvent.KEYCODE_MENU) {
					if (pop != null && pop.isShowing()) {
						pop.dismiss();
					}
				}
				return false;
			}
		});

	}

}